import Vue from 'vue'
import { mapGetters } from 'vuex'
import MSearch from '../components/m-search/index.vue'
import MTable from '../components/m-iview/components/m-table/index.vue'
import MSpin from '../components/m-spin/index.vue'
import { dateFormat, fmtWeekDay, getEndDate, getStartDate, weekDay } from './dateFmt'
import { queryAllByKey } from '@/storm/vertin.ts'

Vue.mixin({
  components: { MSpin, MTable, MSearch },
  data () {
    return {
      colorList: [
        '#F1737D',
        '#F4A873',
        '#FFF100',
        '#C2DE84',
        '#86D192',
        '#73CAC5',
        '#73CBF3',
        '#73ACD7',
        '#8385BE',
        '#A881BD',
        '#C377BB',
        '#F073B9',
        '#F1739E',
        '#AD9276'
      ],
      shopSkuType: [
        {
          value: 'PHYSICAL',
          name: '实物商品',
          code: 0
        },
        {
          value: 'VIRTUAL',
          name: '虚拟商品',
          code: 1
        },
        {
          value: 'COUPON',
          name: '优惠券',
          code: 2
        }
      ],
      colorListTop: {
        '#7D7BA1': '#EEEEFC',
        '#BA78E5': '#BA78E5',
        '#8D81F5': '#F7F1FE',
        '#6995EC': '#F1F5FC',
        '#6DB7E8': '#EFF7FC',
        '#EC6D6D': '#FBEEEE',
        '#EE64C9': '#FCEFF7',
        '#EC9C72': '#FEF4EF',
        '#F3C169': '#FEF8F1',
        '#ECD95E': '#FCFAEF',
        '#FB718D': '#FB718D',
        '#F1FEF7': '#62DE87',
        '#77D9C6': '#77D9C6',
        '#70EBDA': '#EEFCF7',
        '#77D6E1': '#F1FCFE',
        '#9A9A9A': '#F5F5F5'
      },
      courseList: [],
      packageSearchList: [],
      studentSourceList: [],
      followUpStatusList: [],
      dateRangeOption: {
        shortcuts: [
          {
            text: '今天',
            value () {
              const date = new Date(new Date().toLocaleDateString())
              const start = new Date(date.getTime())
              const end = new Date()
              end.setTime(date.getTime() + 3600 * 1000 * 24 * 1 - 1)
              return [start, end]
            }
          },
          {
            text: '最近3天',
            value () {
              const date = new Date(new Date().toLocaleDateString())
              const end = new Date(date.getTime())
              const start = new Date()
              start.setTime(date.getTime() - 3600 * 1000 * 24 * 2)
              return [start, end]
            }
          },
          {
            text: '最近7天',
            value () {
              const date = new Date(new Date().toLocaleDateString())
              const end = new Date(date.getTime())
              const start = new Date()
              start.setTime(date.getTime() - 3600 * 1000 * 24 * 6)
              return [start, end]
            }
          },
          {
            text: '最近15天',
            value () {
              const date = new Date(new Date().toLocaleDateString())
              const end = new Date(date.getTime())
              const start = new Date()
              start.setTime(date.getTime() - 3600 * 1000 * 24 * 14)
              return [start, end]
            }
          },
          {
            text: '最近30天',
            value () {
              const date = new Date(new Date().toLocaleDateString())
              const end = new Date(date.getTime())
              const start = new Date()
              start.setTime(date.getTime() - 3600 * 1000 * 24 * 29)
              return [start, end]
            }
          }
        ]
      },
      dateBaseOption: {
        shortcuts: [
          {
            text: '今天',
            value () {
              return new Date()
            }
          },
          {
            text: '昨天',
            value () {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              return date
            }
          },
          {
            text: '一周后',
            value () {
              const date = new Date()
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
              return date
            }
          }
        ],
        disabledDate: (date) => {
          let disabled = false
          const now = new Date()
          now.setHours(0)
          now.setMinutes(0)
          now.setSeconds(0)
          now.setMilliseconds(0)
          if (this.append) {
            if (date.getTime() < now.getTime()) { disabled = true }
          }
          return disabled
        }
      },
      futureDateRangeOptions: {
        shortcuts: [
          {
            text: '今天',
            value () {
              const start = getStartDate()
              const end = getEndDate()
              return [start, end]
            }
          },
          {
            text: '最近3天',
            value () {
              const start = getStartDate()
              const end = getEndDate(2)
              return [start, end]
            }
          },
          {
            text: '最近7天',
            value () {
              const start = getStartDate()
              const end = getEndDate(6)
              return [start, end]
            }
          },
          {
            text: '最近15天',
            value () {
              const start = getStartDate()
              const end = getEndDate(14)
              return [start, end]
              return [getStartDate(), getEndDate(14)]
            }
          },
          {
            text: '最近30天',
            value () {
              const start = getStartDate()
              const end = getEndDate(29)
              return [start, end]
            }
          }
        ]
      },

      pastDateRangeOptions: {
        shortcuts: [
          {
            text: '今天',
            value () {
              const start = getStartDate()
              const end = getEndDate()
              return [start, end]
            }
          },
          {
            text: '最近3天',
            value () {
              const start = getStartDate(-2)
              const end = getEndDate()
              return [start, end]
            }
          },
          {
            text: '最近7天',
            value () {
              const start = getStartDate(-6)
              const end = getEndDate()
              return [start, end]
            }
          },
          {
            text: '最近15天',
            value () {
              const start = getStartDate(-14)
              const end = getEndDate()
              return [start, end]
            }
          },
          {
            text: '最近30天',
            value () {
              const start = getStartDate(-29)
              const end = getEndDate()
              return [start, end]
            }
          }
        ]
      },
      moduleSourceMap: {
        index: 'index',
        service: 'service',
        renewal: 'renewal'
      }
      // userList:[],
      // followerUserList:[],
      // classList:[],
      // studentList:[],
      // defaultCourseList:[]
    }
  },
  computed: {
    ...mapGetters({
      userList: 'userList',
      allUserList: 'allUserList',
      followerUserList: 'followerUserList',
      // enumsList: 'enums',
      classList: 'classList',
      studentList: 'studentList',
      // defaultCourseList: 'defaultCourseList',
      userType: 'userType',
      memberInfo: 'memberInfo',
      systemVersion: 'systemVersion',
      btnPermission: 'btnPermission',
      accountList: 'accountList',
      userInfo: 'userInfo',
      tabMenuList: 'tabMenuList'
    }),
    fmtClassName () {
      return function (id) {
        const classObj = this.classList.find(item => item.id === id)
        return classObj ? classObj.name : ''
      }
    },
    fmtCourseName () {
      return function (id) {
        const courseList = this.courseList.find(item => item.id === id)
        return courseList ? courseList.courseTitle : ''
      }
    },
    fmtStudentName () {
      return function (id) {
        const studentList = this.studentList.find(item => item.id === id)
        return studentList ? studentList.name : ''
      }
    },
    showTagColor () {
      return function (row, key, enumsKey, tagColorList) {
        let c = ['orange', 'geekblue', 'purple', 'green', 'gold', 'magenta', 'volcano', 'cyan']
        if (tagColorList) { c = tagColorList }

        if (row[key] !== undefined && row[key] !== null) {
          const list = this.getEnums(enumsKey)
          const result = list.find((item) => {
            return item.code === Number.parseInt(row[key])
          })
          return result ? c[result.code] : ''
        } else {
          return ''
        }
      }
    },
    hasPermission () {
      return (permission) => {
        if (typeof permission === 'string') { return this.btnPermission.includes(permission) }

        const key = Array.isArray(permission) ? permission : []

        if (key.length === 0) { return true }
        let result = false
        key.some((perm) => {
          if (this.btnPermission.includes(perm)) {
            result = true
            return true
          }
        })
        return result
      }
    }
  },
  methods: {
    initFollowerUserList () {
      queryAllByKey(this.$store.state.vertin)
      // this.$serverApi.getAllByKey({ containDeleted: true }).then((res) => {
      //   if (res.success) {
      //     this.followerUserList = this.$store.state.vertin.userList.filter(item => Number.parseInt(item.type) !== 2)
      //     this.$store.state.vertin.followerUserList = [...this.followerUserList]
      //     console.log('看看数据', this.followerUserList)
      //   }

      // })
    },
    getAllSimpleStudent () {
      // 留着不要删除
    },
    fmtDate (time) {
      if (!time) { return '' }

      return dateFormat('YYYY-mm-dd', new Date(time))
    },
    fmtDatetime (time) {
      if (!time) { return '' }

      return dateFormat('YYYY-mm-dd HH:MM:SS', new Date(time))
    },
    weekDay (date) {
      return weekDay(date)
    },
    fmtWeekDayTime (time) {
      if (!time) { return '' }

      return (
        `${dateFormat('YYYY-mm-dd', new Date(time))
                }(${
                fmtWeekDay(time)
                }) ${
                dateFormat('HH:MM', new Date(time))}`
      )
    },
    fmtWeekDay (date) {
      return fmtWeekDay(date)
    },
    getUserNameById (id) {
      if (!this.userList) return ''
      const result = this.userList.find(item => item.id === id)
      if (result) { return result.nickname } else { return '' }
    },

    getUserNamesByIds (userIds) {
      let str = ''
      let username = ''
      userIds.forEach((id, index) => {
        username = this.getUserNameById(id) ? this.getUserNameById(id) : '未知'
        if (index !== userIds.length - 1) { str = `${str + username} , ` } else { str += username }
      })
      return str
    },
    getFollowupStatusNameById (id) {
      const result = this.followUpStatusList.find(item => item.id === id)
      if (result) { return result.name } else { return '' }
    },
    getEnumsValue (enumsValue, key) {
      return this.getEnums(enumsValue).find(item => item.code === key) || {}
    },
    getAllEnums () {
      return this.$enum || {}
    },
    getEnums (enumsValue) {
      return this.$enum[enumsValue] || []
    },
    getAllCourse (params = {}) {
      this.$serverApi.getAllCourse(params).then((res) => {
        if (res.success && res.data) { this.courseList = res.data }
      })
      /*            let type = params.courseType ? params.courseType : 0
                        if (params.status !== null && params.status !== undefined) {
                            this.courseList = this.defaultCourseList.filter(item => item.courseType === type && item.status === params.status)
                        } else {
                            this.courseList = this.defaultCourseList.filter(item => item.courseType === type)
                        } */
    },
    getCurCampus () {
      return localStorage.getItem('x-tenant-header')
    },
    queryAllSimpleClass () {
      // 先放着
    },
    getStudentSource () {
      this.$serverApi.getStudentSource({}).then((res) => {
        if (res.success) { this.studentSourceList = res.data }
      })
    },
    getStudentFollowupStatus () {
      this.$serverApi.getStudentFollowupStatus({}).then((res) => {
        if (res.success) { this.followUpStatusList = res.data }
      })
    },
    getAllPackage () {
      this.$serverApi.getSimplePackageInfoList({}).then((res) => {
        if (res.success) { this.packageSearchList = res.data }
      })
    },
    handleParams (param) {
      Object.keys(param).map((key) => {
        if (Array.isArray(param[key])) {
          const arr = []
          param[key].forEach((row) => {
            if (row) { arr.push(row) }
          })
          param[key] = arr
          if (arr.length === 0) { delete param[key] }
        } else if (param[key] === '') {
          delete param[key]
        }
      })
      return param
    }
  }

})
